package gsjob

import (
	"time"

	"gitee.com/crack007/goose/gslog"
	"github.com/robfig/cron/v3"
)

// 定时任务配置(优先级: AtTime > CronExpression > Every)
type ScheduleConfig struct {
	CronExpression string        // 标准cron表达式
	Every          time.Duration // 固定间隔
	AtTime         time.Time     // 指定执行时间
}

type Job struct {
	job    cron.Job
	Name   string
	JobId  cron.EntryID
	config *ScheduleConfig
	cron   *cron.Cron
}

func NewJob(name string, config *ScheduleConfig, job cron.Job) *Job {
	j := &Job{
		Name:   name,
		job:    job,
		config: config,
		cron:   cron.New(),
	}

	var schedule cron.Schedule
	var err error

	// 优先级: AtTime > CronExpression > Every
	if !config.AtTime.IsZero() {
		schedule = cron.ConstantDelaySchedule{
			Delay: time.Until(config.AtTime),
		}
	} else if config.CronExpression != "" {
		schedule, err = cron.ParseStandard(config.CronExpression)
		if err != nil {
			panic(err)
		}
	} else if config.Every > 0 {
		schedule = cron.Every(config.Every)
	} else {
		panic("invalid schedule config")
	}

	j.JobId = j.cron.Schedule(schedule, job)
	return j
}

// 提交定时任务
func (x *Job) Submit() {
	if !initCronStatus {
		Register()
	}
	gslog.Trace("push job-> name: %s, jobId: %d", x.Name, x.JobId)
	x.cron.Start()
}

// 取消定时任务
func (x *Job) Cancel() {
	gslog.Trace("cancel job-> name: %s, jobId: %d", x.Name, x.JobId)
	x.cron.Stop()
	x.cron.Remove(x.JobId)
}
